package com.cg.utils;

import com.cg.common.KeyCommon;
import com.cg.vo.LoginUserVo;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @ClassName TokenUtil
 * @Description 创建Token工具类
 * @Author CG
 * @Date 2023/12/6 11:27
 **/
public class TokenUtil {

    public static String createToken(LoginUserVo loginUserVo){
        //PC端: token:PC-LOGINNAME[加密]-USERID-CREATIONDATE-RONDEM[6位]
        //拼接Token信息
        StringBuffer stringBuffer = new StringBuffer(KeyCommon.USER_TOKEN_KEY);
        //获取LoginName
        String loginName = loginUserVo.getLoginName();
        //拼接
        stringBuffer.append(loginName);
        stringBuffer.append("-");
        //获取USERID
        Integer userId = loginUserVo.getUserId();
        //拼接
        stringBuffer.append(userId.toString());
        stringBuffer.append("-");
        //获取时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        //拼接时间
        stringBuffer.append(simpleDateFormat.format(date));
        stringBuffer.append("-");
        //获取随机的6位
        //先获取生成的UUID，然后再截取最后的6位
        String uuid = UUID.randomUUID().toString();
        stringBuffer.append(uuid.substring(uuid.length()-6));
        return stringBuffer.toString();
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public static Integer getUserIdByToken(String token){
        String[] array = token.split("-");
        Integer userId = Integer .parseInt(array[2]);
        return userId;
    }

}
